﻿using Infragistics.Win.UltraMessageBox;
using OrBitDataModule.Common;
using OrBitDataModule;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TouchSocket.Sockets;
using OrBitDataModule.Contract;
using System.Text.RegularExpressions;

namespace OrBitDataModule.Dialog
{
    public partial class AddRunningTask : Form
    {
        public string UniqueId { get; private set; }
        public string TaskName { get; private set; }
        public bool AutoStart { get; private set; }

        public Dictionary<string, string> Parameters => listView1.Items.Cast<ListViewItem>().ToDictionary(i => i.SubItems[0].Text, i => i.SubItems[1].Text);

        private readonly bool IsEdit;

        public AddRunningTask(bool isEdit, string uniqueId, string taskName)
        {
            InitializeComponent();
            this.IsEdit = isEdit;
            if (isEdit)
            {
                this.UniqueId = uniqueId;
                this.TaskName = taskName;
                this.Text = "修改运行任务"; 
            }
            else
            {
                this.Text = "添加运行任务";
            }
            this.Load += AddRunningTask_Load;

            this.btn_save.Click += Btn_save_Click;
            this.btn_close.Click += Btn_close_Click;
        }

        private async void AddRunningTask_Load(object sender, EventArgs e)
        {
            cbox_taskList.DisplayLayout.Bands[0].Columns["UniqueId"].Hidden = true;
            cbox_taskList.DisplayLayout.Bands[0].Columns["TaskName"].Header.Caption = "任务名称";
            cbox_taskList.DisplayLayout.Bands[0].Columns["TaskName"].Width = 200;
            cbox_taskList.DisplayLayout.Bands[0].Columns["TaskType"].Header.Caption = "任务类型";
            cbox_taskList.DisplayLayout.Bands[0].Columns["TaskType"].Width = 200;
            cbox_taskList.DisplayLayout.Bands[0].Columns["ScriptName"].Header.Caption = "脚本名称";
            cbox_taskList.DisplayLayout.Bands[0].Columns["ScriptName"].Width = 200;
            cbox_taskList.DisplayLayout.Bands[0].Columns["ApiName"].Header.Caption = "接口名称";
            cbox_taskList.DisplayLayout.Bands[0].Columns["ApiName"].Width = 200;

            cbox_taskList.ValueMember = "UniqueId";
            cbox_taskList.DisplayMember = "TaskName";


            listView1.Items.Clear();

            var result = await TaskApi.GetAllTask();
            cbox_taskList.DataSource = result.TaskList.Select(t => new { t.UniqueId, t.TaskName, t.TaskType, t.ScriptName, t.ApiName }).ToList();
            if (IsEdit)
            {
                cbox_taskList.Text = this.TaskName;
                var config = LocalSetting.GetConfig(this.UniqueId);
                cb_autoStart.Checked = config.result;

                foreach (var item in config.parameters)
                {
                    AddRow(item.Key, item.Value);
                }
            }
        }

        private void Btn_save_Click(object sender, EventArgs e)
        {
            string uniqueId = cbox_taskList.Value?.ToString();
            if (IsEdit)
            {
                this.UniqueId = uniqueId;
                this.AutoStart = cb_autoStart.Checked;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(uniqueId))
                {
                    if (LocalSetting.CheckConfigExists(uniqueId))
                    {
                        UltraMessageBoxManager.Show(this, "任务已存在，不允许重复添加", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    this.UniqueId = uniqueId;
                    this.AutoStart = cb_autoStart.Checked;
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
        }

        // 手动新增行
        private bool AddRow(string parameterName, string parameterValue)
        {
            foreach (ListViewItem item in listView1.Items)
            {
                if (item.SubItems[0].Text == parameterName && item.SubItems[1].Text == parameterValue)
                {
                    UltraMessageBoxManager.Show(this, "已存在相同的项目，不允许新增！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            listView1.Items.Add(new ListViewItem(new[] { parameterName, parameterValue }));
            return true;
        }

        // 删除选中行
        private void DeleteSelectedRow()
        {
            if (listView1.SelectedItems.Count > 0)
            {
                listView1.SelectedItems[0].Remove();
            }
        }

        private void Btn_close_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) => DeleteSelectedRow();
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) => e.Cancel = listView1.SelectedItems.Count <= 0;

        private void btn_addParameter_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ute_parameterName.Text))
            {
                UltraMessageBoxManager.Show(this, "参数名称不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrWhiteSpace(ute_parameterValue.Text))
            {
                UltraMessageBoxManager.Show(this, "参数值不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (AddRow(ute_parameterName.Text, ute_parameterValue.Text))
            {
                ute_parameterName.Text = ute_parameterValue.Text = string.Empty;
            }
        }
    }
}
